<?php
require_once 'config.php';
require_once('database.php');

class User extends MySQLDatabase {
	
	public $uid;
	public $username;
	public $password;
	
	public function __construct(){
	
		$is_logged_in = FALSE;
	
	}

	public function insert($tablename, $username, $password){
		global $database;
		$sql = "INSERT INTO users(username, password) ";
		$sql .= "VALUES('$username', '$password')";
		$result = $database->query($sql);
		if($result){
			
			return TRUE;
		
		} else {
		
			return FALSE;
		
		}
	}
	
	public static function find_by_id($uid=0){
		// return an object populated based on user id
		global $database;
		$user = new User();
		
		$sql = "SELECT * FROM users ";
		$sql .= "WHERE  id=${uid} ";
		$sql .= "LIMIT 1";
		
		$result = $database->query($sql);
	
		if($database->num_rows($result)){
			$row = $database->fetch_assoc($result);
			$user->username = $row['username'];
			$user->password = $row['password'];
			$user->id = $uid;
		}
		
		return $user;

	}
	
	public static function find_by_username($username){
		// return an object populated based on user id
		global $database;
		$user = new User();
		
		$sql = "SELECT * FROM users ";
		$sql .= "WHERE  username = '" . $username . "' ";
		$sql .= "LIMIT 1";
		
		$result = $database->query($sql) or die(mysql_error());
	
		if($database->num_rows($result)){
			$row = $database->fetch_assoc($result);
			$user->username = $row['username'];
			$user->password = $row['password'];
			$user->id = $row['id'];
		}
		
		return $user;

	}
	
	public function find_all(){
	
		global $database;
		
		$sql = "SELECT * FROM users";
		$object_array = array();
		
		$result_set = $database->query($sql); 
	
		while($result = $database->fetch_assoc($result_set)){
		
			$object_array[] = $result;
		
		}
		
		return $object_array;
	}
	
	public function delete($uid=0){
	
		global $database;
		
		$sql = "DELETE FROM users ";
		$sql .= "WHERE id = ${uid} ";
		$sql .= "LIMIT 1";
		
		$database->query($sql);
	
		if($database->affected_rows() == 1){
		
			return TRUE;
		
		} else {
		
			return FALSE;
		
		}
	}
	
	public function update($id, $data){
		
		global $database;

		$sql = "UPDATE users ";
		$sql .= "SET username = '" . $data['username'] . "', password = '" .  $data['password'] . "' ";
		$sql .= "WHERE id =" . $id;

		$result = $database->query($sql);
		
		if(!$result){
			die(mysql_error());
		}
		
		if($database->affected_rows($result)){
		
			return TRUE;
		
		}
		
		return FALSE;
		
	
	}


}